#include "head_cli.h"

/**
 * put_cmd -上传文件命令功能函数
 * @addr: 连接到服务器端的socket地址
 * @cmd: 执行的命令字符串
 *
*/
/*
1.建立通讯
2.查看文件
3.发送文件
*/
void put_cmd(struct sockaddr_in client, char *Cmd)
{
	int sockfd = -1;
	//socklen_t len;
	int ret;
	char buffer[N]; //接收数据
	char filename[N];//存放文件名
	int fd;
	int nbytes; //读取的字节数
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if (sockfd < 0) {
		perror("socket");
		exit(1);
	}
	//拨打
	//len = sizeof(client);
	//我打给   client
	ret = connect(sockfd, (struct sockaddr *)&client, sizeof(client));
	if (ret < 0) {
		perror("connect");
		exit(1);
	}
	//发数据给服务端     //返回写入的字节数，失败为-1
	if (write(sockfd, Cmd, strlen(Cmd)) < 0) { //发送命令给服务器端 put xxx
		printf("write error at cmd_put 1\n");
		exit(1);
	}

	//等待应答
	bzero(buffer, N);
	read(sockfd, buffer, N);
	//read(sockfd, buffer, sizeof(buffer));

	//判断buffer是否为ok
	if(!strncmp(buffer, "ok", 2) == 0){
		printf("服务器应答失败\n");
		return ;
	} 

//保留一下，笑个几天	
//	if(!strncpy(buffer, "ok\n", 2) == 0){
//		printf("服务器应答失败\n");
//		return ;
//	} 
	printf("hello world!!!!!!!!\n");
	//获取文件名  //cp Cmd
	bzero(filename, N);
	strncpy(filename, Cmd + 4, strlen(Cmd + 4)); //外部减掉\n
	printf("文件名：%s\n",filename);

	//打开文件
	fd = open(filename, O_RDONLY);
	if(fd < 0){
		printf("文件不存在\n");
		perror("open");
		write(sockfd,"error\n",N);
	}
	write(sockfd, "success\n", N);

	//等待服务端消息
	bzero(buffer, N);
	read(sockfd, buffer, N);//读取服务器端应答 "ok"
	printf("读取到的数据 = %s\n",buffer);
	if(!strncmp(buffer, "ok", 2)==0){
		printf("读取失败");
		return ;
	}
	
	//下面开始上传文件的大小
	struct stat st;
	fstat(fd, &st); //获取filename的文件属性对象
	unsigned long size = st.st_size;
	unsigned long count = 0;
	printf("file size %ld\n",size);

	while (1){
		//system("clear");
		bzero(buffer, N);
		nbytes = read(fd, buffer, N);
	if(nbytes == 0) //读完
		break;
	ret = write(sockfd, buffer, nbytes);
	if(ret < 0){
		printf("数据上传失败\n");
		perror("write");
	}
	printf("nbytes = %d\n",nbytes);
	//进度条
# if 0	
		printf(PURPLE"\n\n\t\t**************** 上传 ******************\n");
		printf("\t\t********** put %s  %ld%% ********\n",filename,count*100/size);
		printf("\t\t****************************************\n"NONE);
#else
	system("clear");
	printf("\t\t********** put %s  %ld%% ********\n",filename,count*100/size);
	usleep(20000);
#endif
	}

# if 0

	printf(PURPLE"\n\n\t\t**************** 上传 ******************\n");
	printf("\t\t********** put %s  %ld%% ********\n",filename,count*100/size);
	printf("\t\t****************************************\n"NONE);

#else
	system("clear");
	printf("\t\t********** put %s  %ld%% ********\n",filename,count*100/size);
#endif


	close(fd);
	close(sockfd);

	
	printf("文件上传成功\n");


	
	printf("execute upload ... \n");
}	


